from dao.DAOQuanLyNhanVien import DaoQuanLyNhanVien
from datetime import datetime as dt
import datetime
from google.appengine.api import users
from google.appengine.ext import db
import json as simplejson
from models.ChiTieuKinhDoanh import ChiTieuKinhDoanh
from models.LoaiNhanVien import LoaiNhanVien
from models.NhanVien import NhanVien
from utils.permission_required import permission_required
import WSGI
import logging
import math
import webapp2

logger = logging.getLogger("GUIChiTieuKinhDoanh")

class GuiChiTieuKinhDoanh(webapp2.RequestHandler):
    priv = ''
    perm = 'QuanLy.ChiTieuKinhDoanh'
    @permission_required
    def get(self):
        cbbTenNV, _ = DaoQuanLyNhanVien.getListNhanVien('', '', 1000, 0, '')
        lstNV = ''
        for i in range(0, cbbTenNV.__len__()):
            cbbTenNV[i]['tenNV'] = str(cbbTenNV[i]['id']) + ' - ' + cbbTenNV[i]['tenNV']
            lstNV += str(cbbTenNV[i]['id']) + ':' + cbbTenNV[i]['tenNV'] + ';'
        lstNV = lstNV[:-1]  
        
        nv = DaoQuanLyNhanVien.getNhanVienByUsername(users.get_current_user().nickname())
        lstPerm = DaoQuanLyNhanVien.getListStaffPriviledge(nv.key().id())
        lstMenu = []
        lstNewPerm = []
        for perm in lstPerm:
            lstMenu.append(perm[:perm.index('.')])
            lstNewPerm.append(perm.replace('.', '-'))
        lstMenu = list(set(lstMenu))
        template_values = {
                        'lstPerm': lstNewPerm,
                        'lstMenu': lstMenu,
                        'cbbTenNV': cbbTenNV,
                        'lstNV': lstNV,
                        'nickname': users.get_current_user().nickname(),
                        'signOutUrl': users.create_logout_url(self.request.uri)
        }

        template = WSGI.jinja_environment.get_template('/html/ChiTieuKinhDoanh.html')
        self.response.out.write(template.render(template_values))


class JsonRequestHandler(webapp2.RequestHandler):
    priv = ''
    perm = 'QuanLy.ChiTieuKinhDoanh'
    @permission_required
    def get(self):
        funcName = self.request.get('func')
        funcMapping = {'getListChiTieuKinhDoanh': 'getListChiTieuKinhDoanh',
                       'updateChiTieuKinhDoanh': 'updateChiTieuKinhDoanh'}
        func = getattr(self, funcMapping[funcName]);
        result = func();
        self.response.out.write(result)
    
    def post(self):
        return self.get()
    
    def getListChiTieuKinhDoanh(self):
        gridRowNum = int(self.request.get('rows'))
        pageNum = int(self.request.get('page'))
        maNV = self.request.get('maNV')
        thang = self.request.get('thang')
        nam = self.request.get('nam')
        rows, rowNum = DaoQuanLyNhanVien.getListChiTieuKinhDoanh(maNV, thang, nam, gridRowNum, int((pageNum-1)*gridRowNum))
        results = {'page': pageNum, 'total': math.ceil(float(rowNum)/gridRowNum), 'records':rowNum, 'rows':rows}
        return simplejson.dumps(results)
    
    def updateChiTieuKinhDoanh(self):
        id = self.request.get('id')
        now = dt.now() + datetime.timedelta(hours=7)
        if id != '_empty':
            ctkd = ChiTieuKinhDoanh.get_by_id(int(id))
        else:
            ctkd = ChiTieuKinhDoanh()
        oper = self.request.get('oper')
        logger.debug(oper)
        if oper == 'del':
            if ctkd.nam <= now.year and ctkd.thang < now.month:
                return 0
            DaoQuanLyNhanVien.deleteChiTieuKinhDoanh(ctkd)
            return 1
        else:
            thang = int(self.request.get('thang'))
            nam = int(self.request.get('nam'))
            if nam <= now.year and thang < now.month:
                return 0
            ctkd.maNV = int(self.request.get('tenNV'))
            ctkd.tenNV = DaoQuanLyNhanVien.getNhanVienById(ctkd.maNV).tenNV
            ctkd.thang = thang
            ctkd.nam = nam
            ctkd.doanhSo = int(self.request.get('doanhSo'))
            
            DaoQuanLyNhanVien.createOrUpdateChiTieuKinhDoanh(ctkd)
            return 1
        
        
            
        